package com.ruoyi.controller;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.domain.Article;
import com.ruoyi.domain.ConlumnMenu;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.mapper.ConlumnMapper;
import com.ruoyi.service.ConlumnMenuService;
import com.ruoyi.system.mapper.SysDeptMapper;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.domain.Conlumn;
import com.ruoyi.service.IConlumnService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import static com.ruoyi.framework.datasource.DynamicDataSourceContextHolder.log;

/**
 * 栏目管理Controller
 * 
 * @author ruoyi
 * @date 2025-01-25
 */
@ApiModel(value = "栏目管理")
@RestController
@RequestMapping("/conlumn/conlumn")
public class ConlumnController extends BaseController
{
    @Autowired
    private IConlumnService conlumnService;

    @Autowired
    TokenService tokenService;
    @Autowired
    private ConlumnMapper conlumnMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private ConlumnMenuService conlumnMenuService;

    @Autowired
    private FileStorageService fileStorageService;//注入实列



    /**
     * 查询栏目管理列表
     */
//    @PreAuthorize("@ss.hasPermi('conlumn:conlumn:list')")


    /**
     * 判断部门是否直接隶属于荆州市长江河道管理局（一级子部门）
     * @param dept 部门信息
     * @return 是否直接隶属于荆州市长江河道管理局
     */
    private boolean isDirectSubDeptOfJingZhou(com.ruoyi.common.core.domain.entity.SysDept dept) {
        // 如果部门本身就是"荆州市长江河道管理局"，则不认为是其下级部门
        if ("荆州市长江河道管理局".equals(dept.getDeptName())) {
            return false;
        }
        
        // 直接检查父部门是否为"荆州市长江河道管理局"
        // 如果父部门ID有效，直接查询父部门名称
        if (dept.getParentId() != null && dept.getParentId() > 0) {
            com.ruoyi.common.core.domain.entity.SysDept parentDept = sysDeptMapper.selectDeptById(dept.getParentId());
            if (parentDept != null && "荆州市长江河道管理局".equals(parentDept.getDeptName())) {
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * 判断部门是否为市局/总局或其子部门
     * @param dept 部门信息
     * @return 是否为市局/总局或其子部门
     */
    private boolean isCityBureauOrSubordinate(com.ruoyi.common.core.domain.entity.SysDept dept) {
        if (dept == null) {
            return false;
        }
        
        // 如果当前部门就是市局/总局，直接返回true
        if ("市局/总局".equals(dept.getDeptName())) {
            return true;
        }
        
        // 通过祖先部门查找是否属于市局/总局
        String ancestors = dept.getAncestors();
        if (ancestors != null && !ancestors.isEmpty()) {
            // 从 ancestors 中提取所有祖先部门ID
            String[] ancestorIds = ancestors.split(",");
            
            // 查询祖先部门中是否有市局/总局
            for (String ancestorId : ancestorIds) {
                if (!ancestorId.trim().isEmpty()) {
                    try {
                        Long deptId = Long.parseLong(ancestorId.trim());
                        com.ruoyi.common.core.domain.entity.SysDept ancestorDept = sysDeptMapper.selectDeptById(deptId);
                        if (ancestorDept != null && "市局/总局".equals(ancestorDept.getDeptName())) {
                            return true;
                        }
                    } catch (NumberFormatException e) {
                        // 忽略无效ID
                    }
                }
            }
        }
        
        return false;
    }

    /**
     * 根据用户所属部门判断是否具有管理权限
     * @param sysUser 用户信息
     * @return 是否具有管理权限
     */
    private boolean hasManagerPermission(SysUser sysUser) {
        String userName = sysUser.getUserName();

        // 判断是否为管理员账户
        boolean isSuperAdmin = "admin".equals(userName);
        boolean hasManagerPermission = isSuperAdmin;

        // 如果不是超级管理员，则检查部门权限
        if (!isSuperAdmin && sysUser.getDept() != null) {
            // 获取用户所属部门
            String deptName = sysUser.getDept().getDeptName();
            com.ruoyi.common.core.domain.entity.SysDept dept = sysUser.getDept();

            // 根据部门类型判断权限：
            if (deptName != null) {
                if ("市局/总局".equals(deptName)) {
                    // 市局/总局具有管理权限
                    hasManagerPermission = true;
                } else if (isDirectSubDeptOfJingZhou(dept)) {
                    // 直接隶属于荆州市长江河道管理局的部门（分局）不具有管理权限
                    hasManagerPermission = false;
                } else if (isCityBureauOrSubordinate(dept)) {
                    // 市局/总局的子部门具有管理权限
                    hasManagerPermission = true;
                } else {
                    // 其他部门，默认不具有管理权限
                    hasManagerPermission = false;
                }
            }
        }

        return hasManagerPermission;
    }


    /**
     * 查询栏目管理列表
     */
    @GetMapping("/list")
    //@PreAuthorize("hasAnyAuthority('admin','common','column_manager')")
    public TableDataInfo list(Conlumn conlumn) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser sysUser = loginUser.getUser();

        // 使用基于部门的权限判断
        boolean hasManagerPermission = hasManagerPermission(sysUser);
        Long deptId = sysUser.getDept() != null ? sysUser.getDept().getDeptId() : null;
        List<Conlumn> list = conlumnService.selectConlumnListByRole(hasManagerPermission, deptId, conlumn);
        return getDataTable(list);
    }


    //获取全部的栏目列表
    @GetMapping("/getColumnList")
    public TableDataInfo getColumnList(Conlumn conlumn) {
        LambdaQueryWrapper<Conlumn> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(conlumn.getName()!=null,Conlumn::getName,conlumn.getName());
        queryWrapper.eq(conlumn.getRole()!=null,Conlumn::getRole,conlumn.getRole());
        List<Conlumn> list=conlumnService.list(queryWrapper);
        return getDataTable(list);
    }

//    //分页获取的栏目列表
//    @GetMapping("/getColumnList2")
//    public TableDataInfo getColumnList2(Conlumn conlumn) {
//        startPage();
//        List<Conlumn> list=conlumnService.selectConlumnList(conlumn);
//        return getDataTable(list);
//    }

    //获取role为1的栏目列表(支持临时权限)
    @GetMapping("/getColumnListByRole")
    public TableDataInfo getColumnListByRole() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser sysUser = loginUser.getUser();
        
        // 使用基于部门的权限判断
        boolean hasManagerPermission = hasManagerPermission(sysUser);
        Long deptId = sysUser.getDept() != null ? sysUser.getDept().getDeptId() : null;
        Conlumn conlumn = new Conlumn();
        List<Conlumn> list = conlumnService.selectConlumnListByRole(hasManagerPermission, deptId, conlumn);
        return getDataTable(list);
    }

    /**
     * 导出栏目管理列表
     */
    @PreAuthorize("@ss.hasPermi('conlumn:conlumn:export')")
    @Log(title = "栏目管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Conlumn conlumn)
    {
        List<Conlumn> list = conlumnService.selectConlumnList(conlumn);
        System.out.println("导出栏目数据："+list);
        ExcelUtil<Conlumn> util = new ExcelUtil<Conlumn>(Conlumn.class);
        util.exportExcel(response, list, "栏目管理数据");
    }

    /**
     * 获取栏目管理详细信息
     */
//    @PreAuthorize("@ss.hasPermi('conlumn:conlumn:query')")
    @Anonymous
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(conlumnService.getById(id));
    }

    @GetMapping( "/getConlumnMe/{id}")
    public AjaxResult getConlumn(@PathVariable("id") Integer id) {
        return AjaxResult.success(conlumnMenuService.getById(id));
    }

    @GetMapping("/listMe")
    public AjaxResult list() {
        return AjaxResult.success(conlumnMenuService.list());
    }

    @GetMapping( "/listMe/{name}")
    public AjaxResult list(@PathVariable String name) {
        LambdaQueryWrapper<ConlumnMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name!=null,ConlumnMenu::getName,name);
        return AjaxResult.success(conlumnMenuService.list(queryWrapper));
    }
    @PreAuthorize("@ss.hasPermi('conlumn:menu:edit')")
    @Log(title = "栏目管理", businessType = BusinessType.UPDATE)
    @PutMapping("/updateMe")
    public AjaxResult updateMenu(@RequestBody ConlumnMenu conlumnMenu) {
        return AjaxResult.success(conlumnMenuService.updateById(conlumnMenu));
    }

    @PreAuthorize("@ss.hasPermi('conlumn:menu:add')")
    @Log(title = "栏目管理", businessType = BusinessType.INSERT)
    @PostMapping("/addMe")
    public AjaxResult addMenu(@RequestBody ConlumnMenu  conlumnMenu) {
        if (conlumnMenuService.save(conlumnMenu)){
            return AjaxResult.success(conlumnMenu.getId());
        }
        return AjaxResult.error("添加失败");
    }


    @PreAuthorize("@ss.hasPermi('conlumn:menu:delete')")
    @Log(title = "栏目管理", businessType = BusinessType.DELETE)
    @Transactional(rollbackFor = Exception.class)
    @DeleteMapping("/delete/{id}")
    public AjaxResult deleteMenu(@PathVariable("id") Integer id) {
        // 检查是否有子节点 - 修复逻辑错误
        if(conlumnMenuService.deleteConlumnMENUById(id) == false){
            return AjaxResult.error("删除失败，该栏目下有子栏目");
        }
        // 没有子节点，执行删除
        boolean result = conlumnMenuService.removeById(id);
        if(result) {
            return AjaxResult.success("删除成功");
        } else {
            return AjaxResult.error("删除失败");
        }
    }

    @PreAuthorize("@ss.hasPermi('conlumn:menu:mobile')")
    @Log(title = "栏目管理", businessType = BusinessType.UPDATE)
    @PostMapping("/mobile")
    public AjaxResult mobile(@RequestBody List<ConlumnMenu> conlumnMenuList) {
        ConlumnMenu conlumnone=conlumnMenuList.get(0);
        ConlumnMenu conlumntwo=conlumnMenuList.get(1);
        if(conlumnone.getParentId()!=conlumntwo.getParentId()){
            return AjaxResult.error("移动失败，请勿移动不同父级栏目");
        }
        int type=conlumnone.getOrderNum();
        conlumnone.setOrderNum(conlumntwo.getOrderNum());
        conlumntwo.setOrderNum(type);
        conlumnMenuService.updateById(conlumnone);
        conlumnMenuService.updateById(conlumntwo);
        return AjaxResult.success();
    }




    /**
     * 新增栏目管理
     */
    @PreAuthorize("@ss.hasPermi('conlumn:conlumn:add')")
    @Log(title = "栏目管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Conlumn conlumn)
    {
        return toAjax(conlumnService.save(conlumn));
    }

    /**
     * 修改栏目管理
     */
    @PreAuthorize("@ss.hasPermi('conlumn:conlumn:edit')")
    @Log(title = "栏目管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Conlumn conlumn)
    {
        return toAjax(conlumnService.updateById(conlumn));
    }

    /**
     * 删除栏目管理
     */
    @PreAuthorize("@ss.hasPermi('conlumn:conlumn:remove')")
    @Log(title = "栏目管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    @Transactional
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        // 检查是否有子栏目
        for (Long id : ids) {
            if (conlumnService.existsChildByParentId(id)) {
                return AjaxResult.error("该栏目下存在子栏目，不能删除");
            }
        }
        return toAjax(conlumnService.deleteConlumnByIds(ids));
    }
    /**
     * 封面路径
     */
    @Anonymous
    @PostMapping("/filePathImg1/{id}/{type}")
    public AjaxResult uploadFile(@PathVariable int id, @RequestParam MultipartFile file, @PathVariable int type) throws Exception {
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return AjaxResult.error("上传文件为空");
            }

            // 获取当前日期用于文件路径
            String datePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));

            // 构建OSS保存文件路径，使用配置的基础路径
            String objectName = "column/images/" + datePath + "/" + file.getOriginalFilename();

            // 上传图片到OSS，成功返回文件信息
            FileInfo fileInfo = fileStorageService.of(file)
                    .setPlatform("aliyun-oss-1") // 明确指定使用阿里云OSS平台
                    .setPath(objectName)
                    .upload();

            // 检查文件是否成功上传到OSS
            if (fileInfo == null || fileInfo.getUrl() == null) {
                return AjaxResult.error("文件上传失败");
            }

            // 设置返回结果
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", fileInfo.getUrl());
            ajax.put("fileName", fileInfo.getFilename());
            ajax.put("newFileName", fileInfo.getUrl());
            ajax.put("originalFilename", file.getOriginalFilename());

            // 更新栏目菜单的图片路径
            ConlumnMenu byId = conlumnMenuService.getById(id);
            if (byId == null){
                return AjaxResult.error("栏目不存在");
            }

            // 根据type设置对应的图片字段
            if (type == 1){
                byId.setImg1(fileInfo.getUrl());
            }else if (type == 2){
                byId.setImg2(fileInfo.getUrl());
            }

            // 更新数据库记录
            boolean updateResult = conlumnMenuService.updateById(byId);
            if (!updateResult) {
                return AjaxResult.error("图片路径保存失败");
            }

            log.info("栏目图片上传成功，路径：" + fileInfo.getUrl());
            return ajax;

        } catch (Exception e) {
            log.error("栏目图片上传异常", e);
            return AjaxResult.error("上传失败: " + e.getMessage());
        }
    }

}
